//
//  ViewController.m
//  MemoryManagerDemo
//
//  Created by FelixYin on 2020/4/11.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "ViewController.h"
#import "FYProxy.h"
#import "FYProxy1.h"

@interface ViewController ()

@property (nonatomic,strong) CADisplayLink *link;
@property (nonatomic,strong) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self addDisplay];
//    [self addTimer];
    [self proxyDifferent];
}

- (void) addDisplay{
//    self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayTest)];
//    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    //使用消息转发机制解决 强引用问题
//    self.link = [CADisplayLink displayLinkWithTarget:[FYProxy proxyWithTarget:self] selector:@selector(displayTest)];
//    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    
    self.link = [CADisplayLink displayLinkWithTarget:[FYProxy1 proxyWithTarget:self] selector:@selector(displayTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}


- (void) addTimer{
    __weak typeof(self) weakSelf = self;
    if (@available(iOS 10.0, *)) {
        //这种方式不会产生强引用
//        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//            [weakSelf timerTest];
//        }];
        
        //这种会产生强引用 （怎么解决强引用？ 可以利用消息转发机制）
//        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerTest) userInfo:nil repeats:YES];
        
        //方案一
//        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[FYProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
//        [self.timer fire];
        
        //方案二
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:[FYProxy1 proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
        [self.timer fire];
    } else {
        // Fallback on earlier versions
    }
}


- (void) displayTest{
    NSLog(@"==== Display");
}

- (void) timerTest{
    NSLog(@"==== Timer");
}

// MARK: NSProxy 与 FYProxy实质性的区别

- (void) proxyDifferent{
    
    UIViewController *vc = [[UIViewController alloc] init];
    FYProxy *proxy = [FYProxy proxyWithTarget:vc];
    FYProxy1 *proxy1 = [FYProxy1 proxyWithTarget:vc];
    
    NSLog(@"%@ === %@",@([proxy isKindOfClass:[UIViewController class]]),@([proxy1 isKindOfClass:[UIViewController class]]));
    //输出结果为 0 === 1
    /*
     原因：FYProxy 继承自NSObject 正常判断当前类是否属于UIViewController的类或者子类，proxy不属于UIViewController类也不是其子类 所以为0
     
     FYProxy1 继承自NSProxy,当前类中isKindOfClass方法内部直接使用的是消息转发机制，所以直接进入消息转发。此时就相当于判断UIViewController
     是否为UIViewController类或者其子类 所以结果输出为 1
     
     */
    
}

 
- (void)dealloc
{
    [self.link invalidate];
    [self.timer invalidate];
    NSLog(@"dealloc");
}

@end
